package android.vstore.fragment;

import gin.dev.update.DownloadQuere;
import gin.dev.update.DownloadTask;
import gin.dev.update.IOnDownload;
import gin.dev.update.Installation;
import it.sephiroth.android.library.widget.AbsHListView;
import it.sephiroth.android.library.widget.AbsHListView.OnScrollListener;
import it.sephiroth.android.library.widget.HListView;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.appvn2014.appstorevn.R;

import DTO.ImageDTO;
import DTO.ProductDTO;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.PopupMenu.OnDismissListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.vstore.activities.BaseActivity;
import android.vstore.activities.SceneDetailItemActivity;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import anroid.vstore.provider.Constant;
import anroid.vstore.provider.Navigator;
import anroid.vstore.provider.UpdateSttListThread;

public class PageHorizalGalleryFragment extends Fragment implements OnClickListener, it.sephiroth.android.library.widget.AdapterView.OnItemClickListener,OnScrollListener {
	
	// Views
	private View v_rootView;
	private TextView tv_title;
	private HListView lv_prods;
	private ProgressBar pb_loader;
	private TextView tv_viewmore;
	
	// Page properties
	int _id;
	String _name;
	ProductListAdapter _adapter;
	BaseActivity _activity;
	String _category;
	int _type;
	
	boolean isReload=true;
	boolean isNomore = false;
	boolean isProductsLoading = false;
	private boolean pauseOnFling =  false;
	private boolean pauseOnScroll = false;
	
	ArrayList<ProductDTO> _lstItem = new ArrayList<ProductDTO>();
	public UpdateSttListThread sttlloader;
	
	
	// Initialize & return PageHorizalGalleryFragment
	public static PageHorizalGalleryFragment instance(BaseActivity activity, int id,String cat,String name)
	{
		PageHorizalGalleryFragment fragment = new PageHorizalGalleryFragment();
		fragment._category = cat;
		fragment._name = name;
		if(fragment._name.equals(""))
			return null;
		fragment.isReload = true;
		fragment._activity =activity;
		fragment._id = id;
		return fragment;
	}
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);


	}
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState); 
		

	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		v_rootView = inflater.inflate(R.layout.fragment_hlistview, container, false);
		InitGUI();	// Initialize GUI components
		Load();	// Start loader
		return v_rootView;
	}
	public void InitGUI()
	{
		tv_title = (TextView)v_rootView.findViewById(R.id.tv_hlistview_label);
		tv_title.setText(_name);
		
		tv_viewmore = (TextView) v_rootView.findViewById(R.id.tv_hlistview_more);
		tv_viewmore.setOnClickListener(this);
		
		lv_prods = (HListView)v_rootView.findViewById(R.id.lv_hlistview);
		pb_loader = (ProgressBar)v_rootView.findViewById(R.id.pb_hlistview_loading);
		
		lv_prods.setOnItemClickListener(this);
		lv_prods.setOnScrollListener(this);

		
		// Recycle row item
//		lv_prods.setRecyclerListener(new RecyclerListener() {
//			
//			@Override
//			public void onMovedToScrapHeap(View view) {
//				// TODO Auto-generated method stub
//				ImageView iv = (ImageView) view.findViewById(R.id.iv_horizalItem_logo);
//				if(iv != null)
//				{
////					Helper.recycle(iv);
////					iv.setImageResource(R.drawable.ic_loading);
//				}
//				
//			}
//		});
		lv_prods.setDividerWidth(10);
		//		lv_prods.setDivider(getResources().getColor(R.color.gray_little));
		HideLoaderPending();
	}
	@Override
	public void onItemClick(
			it.sephiroth.android.library.widget.AdapterView<?> parent,
			View view, int position, long id) {

		Navigator.toDetailItem(_activity,_lstItem.get(position));
	}
	public void Load()
	{
		if(isNomore)
			return;
		if(isReload )	// if true then clear listview
		{
			_lstItem.clear();
		}
		(new Loader()).execute();
		isReload = false;
		
	}
	protected void ShowLoaderPending()
	{		
		pb_loader.setVisibility(View.VISIBLE);
	}
	protected void HideLoaderPending()
	{
		pb_loader.setVisibility(View.INVISIBLE);
	}


	

	public class Loader extends AsyncTask<String, Void, ArrayList<ProductDTO>>{
		private static final int pagesize = 3;

		@Override
		protected ArrayList<ProductDTO> doInBackground(String... params) {
			

			ArrayList<ProductDTO> lstProds = null;
			switch (_id) {
//			case Constant.HORIZALLIST_CATEGORY:
//				lstProds = DAO.ProductDAO.GetProds(_activity, _category, 0,-1, 1, _lstItem.size()+10);
//				break;
			case Constant.HORIZALLIST_COLLECTION:
				lstProds = DAO.ProductDAO.GetCollectionProds(_activity,(String)_category, _lstItem.size()+pagesize);
				break;	
			case Constant.HORIZALLIST_SAMECAT:
				lstProds = DAO.ProductDAO.GetSameCatProds(_activity, (String)_category,_lstItem.size()+pagesize);
				break;
			case Constant.HORIZALLIST_SAMEPUBLISHER:
				lstProds = DAO.ProductDAO.GetSamepublisherProds(_activity, (String)_category,_lstItem.size()+pagesize);
				break;
			default:
				break;
			}
			
			if(lstProds!= null && lstProds.size() < _lstItem.size()+10)
				isNomore= true;
			return lstProds;
		}      

		@Override
		protected void onPostExecute(ArrayList<ProductDTO> lstProd) {
			//			HideLoaderPending();
			isProductsLoading = false;
			if((this == null && !PageHorizalGalleryFragment.this.isDetached() )|| lstProd ==null)
				return;

			if(_lstItem.size() == 0)
			{
				_adapter = new ProductListAdapter(_activity);
				_adapter.update(_lstItem);
				lv_prods.setAdapter(_adapter);
			}
			if(_lstItem != null && _lstItem.size() < lstProd.size())
			{
				int startindx = _lstItem.size();
				_lstItem.addAll(lstProd.subList(startindx, lstProd.size()));
			}
			if(_lstItem != null && _lstItem.size() == 0)
			{
				_activity.getSupportFragmentManager().beginTransaction().remove(PageHorizalGalleryFragment.this).commit();
				return;
			}
			else
				_adapter.notifyDataSetChanged();
			if(sttlloader == null)
			{
				sttlloader = new UpdateSttListThread(_activity, _messageHandler, _lstItem, 0, _lstItem.size());
				sttlloader.Load();
			}else
				sttlloader.LoadMore(_lstItem.size());
		}

		@Override
		protected void onPreExecute() {
			if(isProductsLoading  )
			{
				this.cancel(true);
				return;
			}
			isProductsLoading = true;
			//			ShowLoaderPending();	
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}
	
	public class ProductListAdapter extends BaseAdapter {

	    private List<ProductDTO> itemList = Collections.emptyList();

	    private final Activity context;

	    // the context is needed to inflate views in getView()
	    public ProductListAdapter(Activity context) {
	        this.context = context;
	        
	    }

	    public void update(List<ProductDTO> bananaPhones) {
	        this.itemList = bananaPhones;
//	        notifyDataSetChanged();
	    }

	    @Override
	    public int getCount() {
	        return itemList.size();
	    }

	    // getItem(int) in Adapter returns Object but we can override
	    // it to BananaPhone thanks to Java return type covariance
	    @Override
	    public ProductDTO getItem(int position) {
	        return itemList.get(position);
	    }

	    // getItemId() is often useless, I think this should be the default
	    // implementation in BaseAdapter
	    @Override
	    public long getItemId(int position) {
	        return position;
	    }

	    @Override
	    public View getView(final int position, View convertView, ViewGroup parent) {
	      // Let's look at that later
	    	LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    	final ViewHolderProduct holder;
			if(convertView == null) 
			{
				holder = new ViewHolderProduct();
				convertView = inflater.inflate(R.layout.item_list_horizalprod,parent,false);


				holder.imgViewLogo = (ImageView) convertView.findViewById(R.id.iv_horizalItem_logo);
				holder.txtViewTitle = (TextView) convertView.findViewById(R.id.tv_horizalItem_title);
				holder.txtViewOwner = (TextView) convertView.findViewById(R.id.tv_horizalItem_owner);
				holder.ibtnViewMenu = (ImageView) convertView.findViewById(R.id.ib_horizalItem_menu);
				holder.ibtnViewStatus = (ImageView)convertView.findViewById(R.id.ib_horizalItem_status);
				holder.position = position;
				convertView.setTag(holder);
			}
			else
				holder = (ViewHolderProduct)convertView.getTag();

			final ProductDTO bean = (ProductDTO) itemList.get(position);
			
			if(bean == null) return convertView;
			holder.txtViewOwner.setText(bean.publisher);
			holder.ibtnViewMenu.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(final View v) {
					// TODO Auto-generated method stub
					((ImageView)v).setImageResource(R.drawable.ic_menu);
					
					PopupMenu popup = new PopupMenu(_activity, v);
					popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
					if(itemList.get(position).status == Constant.APP_STT_NOTHING )
					{
						popup.getMenu().getItem(0).setTitle(_activity.getString(R.string.detail_activity_view_app));
						popup.getMenu().getItem(1).setTitle(_activity.getString(R.string.detail_activity_view_detail_app));
					
					}else if(itemList.get(position).status == Constant.APP_STT_DOWNLOADED )
					{
						popup.getMenu().getItem(0).setTitle(_activity.getString(R.string.detail_activity_downloaded_app));
						popup.getMenu().getItem(1).setTitle(_activity.getString(R.string.detail_activity_view_detail_app));
					}else if(itemList.get(position).status == Constant.APP_STT_UPDATE)
					{
						popup.getMenu().getItem(0).setTitle(_activity.getString(R.string.detail_activity_update_app));
						popup.getMenu().getItem(1).setTitle(_activity.getString(R.string.detail_activity_remove_app));
					}else if(itemList.get(position).status == Constant.APP_STT_DOWNLOADING)
					{
						popup.getMenu().getItem(0).setTitle(_activity.getString(R.string.detail_activity_downloading_app));
					}
					else 
					{
						popup.getMenu().getItem(0).setTitle(_activity.getString(R.string.detail_activity_open_app_name));
						popup.getMenu().getItem(1).setTitle(_activity.getString(R.string.detail_activity_remove_app));
					}
					popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
						public boolean onMenuItemClick(MenuItem item) {
							if(item.getItemId() == R.id.add1)
							{
								// Install app
								Option1(position, holder);
							}else if(item.getItemId() == R.id.add2)
							{
								Option2(position, holder);
							}
							//							Toast.makeText(activity,
							//									"You Clicked : " + item.getTitle(),
							//									Toast.LENGTH_SHORT).show();
							return true;
						}
					});
					popup.setOnDismissListener(new OnDismissListener() {
						
						@Override
						public void onDismiss(PopupMenu arg0) {
							// TODO Auto-generated method stub
							((ImageView)v).setImageResource(R.drawable.ic_menu_light);
						}
					});

					popup.show();
				}
			});
			switch (itemList.get(position).status) {
			case Constant.APP_STT_INSTALLED:
				holder.ibtnViewStatus.setVisibility(View.VISIBLE);
				holder.ibtnViewStatus.setImageResource(R.drawable.ic_check);
				break;
			case Constant.APP_STT_UPDATE:
				holder.ibtnViewStatus.setVisibility(View.VISIBLE);
				holder.ibtnViewStatus.setImageResource(R.drawable.ic_update);
				break;
			default:
				holder.ibtnViewStatus.setVisibility(View.INVISIBLE);

				break;
			}
			if (holder.lastImageUrl == null || !holder.lastImageUrl.equals(bean.imgURL)
					|| holder.imgViewLogo.getDrawable() == null) {
				// refresh image
				holder.lastImageUrl = bean.imgURL;
				ImageDTO.displayImage( bean.imgURL, holder.imgViewLogo); 
			}
			
			

			holder.txtViewTitle.setText(bean.name);
			return convertView;
	    }

	    public class ViewHolderProduct
		{
			public String lastImageUrl;
			public ImageView imgViewLogo;
			public TextView txtViewTitle;

			public TextView txtViewOwner;
			public ImageView ibtnViewMenu;
			public ImageView ibtnViewStatus;
			public int position;
		}
	    private void Option1(final int pos, final ViewHolderProduct holder) {
			//			final TextView btn = holder.btnViewAppStatus;

			final ProductDTO item = itemList.get(pos);
//			holder.ivViewStatus.setVisibility(View.INVISIBLE);
			itemList.get(pos).isInvalidated = true;
			if(itemList.get(pos).status == Constant.APP_STT_NOTHING || 
					itemList.get(pos).status == Constant.APP_STT_UPDATE)
			{

				itemList.get(pos).status = Constant.APP_STT_DOWNLOADING;
				String url = SceneDetailItemActivity.URL_HEADER + item.filePath;
				final String packageName = item.packageName;
				DownloadTask downloader = new DownloadTask(context, null, new IOnDownload() {

					@Override
					public void OnFinished() {
						// TODO Auto-generated method stub

						String path = Environment.getExternalStorageDirectory()
								.getAbsoluteFile()
								+ "/Download/" + packageName + ".apk";
						File file = new File(path);
						
						itemList.get(pos).status = Constant.APP_STT_DOWNLOADED;
						itemList.get(pos).isInvalidated = true;
						_adapter.notifyDataSetChanged();
						
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.putExtra("Position", pos);
						intent.setDataAndType(Uri.fromFile(file),
								"application/vnd.android.package-archive");
//						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivityForResult(intent,Constant.RECHECK_ALL_PAGE);

					}

					@Override
					public void OnError() {
						// TODO Auto-generated method stub
					}
				});
				DownloadQuere.Add(context, downloader, item.id, url, item.packageName);
				// Toast
				Toast.makeText(_activity, item.name +getString( R.string.toast_downloading), Toast.LENGTH_LONG).show();
			}
			if(itemList.get(pos).status == Constant.APP_STT_DOWNLOADED)
			{
//				itemList.get(pos).status = Constant.APP_STT_INSTALLING;
				// install app
				String path = Environment.getExternalStorageDirectory()
						.getAbsoluteFile()
						+ "/Download/" + item.packageName + ".apk";
				if(Installation.Install(context, path) == false)
				{
					Log.i("TAG", "Error when open app" + item.packageName);
				}

			}
			if(itemList.get(pos).status == Constant.APP_STT_INSTALLED)
			{
				
				// open app
				if(Installation.OpenApp(context, item.packageName) == false)
				{
					Log.i("TAG", "Error when open app" + item.packageName);
				}
			}
			
		}
	    private void Option2(final int pos, final ViewHolderProduct holder) {
			//			final TextView btn = holder.btnViewAppStatus;

			final ProductDTO item = itemList.get(pos);

			if(itemList.get(pos).status == Constant.APP_STT_NOTHING ||
					itemList.get(pos).status == Constant.APP_STT_DOWNLOADED )
			{
				Navigator.toDetailItem(_activity, itemList.get(pos).id);
			}
			if(itemList.get(pos).status == Constant.APP_STT_INSTALLED|| 
					itemList.get(pos).status == Constant.APP_STT_UPDATE)
			{
				Uri uri = Uri.fromParts("package", item.packageName, null);

				Intent it = new Intent(Intent.ACTION_DELETE, uri);

				startActivityForResult(it,Constant.RECHECK_ALL_PAGE);
			}
			itemList.get(pos).isInvalidated = true;
		}
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(lv_prods != null)
			Invalidate();
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == Constant.RECHECK_ALL_PAGE)
		{
			Invalidate();
		}

	}
	
	@Override
	public void onScrollStateChanged(AbsHListView view, int scrollState) {
		// pause loading when scrolling or flinging
//		switch (scrollState) {
//		case OnScrollListener.SCROLL_STATE_IDLE:
//			imageLoader.resume();
//			break;
//		case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
//			if (pauseOnScroll) {
//				imageLoader.pause();
//			}
//			break;
//		case OnScrollListener.SCROLL_STATE_FLING:
//			if (pauseOnFling) {
//				imageLoader.pause();
//			}
//			break;
//		}
//		if (externalListener != null) {
//			externalListener.onScrollStateChanged(view, scrollState);
//		}
	}
	@Override
	public void onScroll(AbsHListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// if reach to the bottom -> load more
		if(_lstItem != null && !isProductsLoading)
		{
			if(_lstItem.size()-2 > firstVisibleItem && _lstItem.size()-2 < firstVisibleItem+visibleItemCount)
			{
				Load();
			}
		}

	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.equals(tv_viewmore))
		{
			Navigator.toItemList(_activity,_id,_category,_name );
		}
	}
	public Handler _messageHandler = new Handler(){
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == Constant.REFRESH_ALL_PAGE)
			{
				if(_adapter != null)
					_adapter.notifyDataSetChanged();
				ischecking = false;
			}
		}
	};
	private boolean ischecking = false;
	public void Invalidate()
	{
		if(ischecking) return;
		if(sttlloader == null  )
		{
			sttlloader = new UpdateSttListThread(_activity, _messageHandler, _lstItem, 0, _lstItem.size()-1);
			sttlloader.Load();
		}else
		{
			sttlloader._start = 0;
			sttlloader._end = _lstItem.size()-1;
			sttlloader.LoadMore(_lstItem.size());
		}
		
	}
}
